<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      :model="formData"
      ref="formRef"
      :rules="formRules"
      vloading="formLoading"
      label-width="auto"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入名称" :clearable="true" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" prop="areaClassId">
            <el-select v-model="formData.areaClassId" placeholder="请输入分类">
              <el-option
                v-for="dict in classList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用地面积" prop="landArea">
            <InputNumber type="decimal" v-model="formData.landArea" placeholder="请输入用地面积" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="行政区划" prop="administrativeDivision">
            <el-input
              v-model="formData.administrativeDivision"
              placeholder="请输入行政区划"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="建设年代" prop="buildingYears">
            <el-input
              v-model="formData.buildingYears"
              placeholder="请输入建设年代"
              :clearable="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否租借" prop="isLease">
            <el-checkbox v-model="formData.isLease" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="权属登记情况" prop="ownershipRegister">
            <el-input
              v-model="formData.ownershipRegister"
              placeholder="请输入权属登记情况"
              :clearable="true"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22">
          <el-form-item label="详细地址" prop="detailAddress">
            <el-input
              v-model="formData.detailAddress"
              placeholder="请输入详细地址"
              :clearable="true"
              type="textarea"
              class="mr-1"
            />
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-button @click="handleMapSelectAddress" class="w-8 mt-2" type="primary">
            <Icon icon="ep:location" class="ml-0.5" />
          </el-button>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              v-model="formData.remark"
              placeholder="请输入备注"
              :clearable="true"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>

      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
    <MapSelectAddress ref="mapSelectRef" @select-value="handleSelectAddress" />
  </Dialog>
</template>
<script setup name="OfficeAreaEdit" lang="ts">
import * as officeAreaApi from '@/api/area/officeArea'
import * as officeAreaClassApi from '@/api/area/officeAreaClass'
import * as officeAreaModel from '@/model/office/area/OfficeArea'
import MapSelectAddress from '@/views/officeArea/map/MapSelectAddress.vue'
const mapSelectRef = ref()
const message = useMessage()
const { t } = useI18n()
const classList = ref()
let formType = ''
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref({
  name: '',
  areaClassId: '',
  landArea: 0,
  administrativeDivision: '',
  buildingYears: '',
  isLease: false,
  ownershipRegister: '',
  detailAddress: '',
  lng: '',
  lat: '',
  remark: ''
})
const formRules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  areaClassId: [{ required: true, type: 'number', message: '请输入分类', trigger: 'change' }]
})
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  classList.value = await officeAreaClassApi.listQuery()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await officeAreaApi.singleGet(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    name: '',
    areaClassId: '',
    landArea: 0,
    administrativeDivision: '',
    buildingYears: '',
    isLease: false,
    ownershipRegister: '',
    detailAddress: '',
    lng: '',
    lat: '',
    remark: ''
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as officeAreaModel.OfficeArea
    if (formType === 'create') {
      await officeAreaApi.create(data)
      message.success(t('common.createSuccess'))
    } else {
      console.log(data)
      await officeAreaApi.update(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const handleMapSelectAddress = () => {
  mapSelectRef.value.open({
    name: formData.value.detailAddress,
    lng: formData.value.lng,
    lat: formData.value.lat
  })
}

const handleSelectAddress = (selectAddress) => {
  if (selectAddress.name != '') {
    formData.value.detailAddress = selectAddress.name
    formData.value.lng = selectAddress.lng
    formData.value.lat = selectAddress.lat
  }
}
</script>
